package com.ly.hotel.view.setting;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.ly.hotel.R;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.adaptor.NetworkUtil;
import com.ly.hotel.util.AppUtil;
import com.ly.hotel.util.WebInstaller;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class SettingImportActivity extends Activity {
	private String path = "";
	private String mode = "";
	private String ipMacListPath = "";
	private TextView macTxt;
	private TextView ipTxt1;
	private TextView ipTxt2;
	private TextView ipTxt3;
	private TextView ipTxt4;
	private TextView networkMaskTxt;
	private TextView dnsTxt;
	private TextView dns2Txt;
	private TextView gatewayTxt;
	private TextView baudTxt;
	private TextView serverIpTxt;
	private Button okBtn;
	private Button backBtn;
	private String myIp;
	private String newIp;

	private static Properties props = new Properties();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_setting_import);

		Intent intent = getIntent();
		path = intent.getStringExtra("path");
		mode = intent.getStringExtra("mode");
		ipMacListPath = intent.getStringExtra("usbRoot") + "/ipMac.txt";
		Log.i("setting", "文件路径:" + path + ",模式:" + mode + ",IP-MAC列表路径:" + ipMacListPath);

		File file = new File(path);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			props.load(new FileInputStream(path));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.exit(-1);
		} catch (IOException e) {
			System.exit(-1);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (mode.equals("importIp")) {
			initViewForImportIp();
		} else {
			initView();
		}
	}
	
	//
	private void initView() {
		macTxt = (TextView) findViewById(R.id.macTxt);
		ipTxt1 = (TextView) findViewById(R.id.ipTxt1);
		ipTxt2 = (TextView) findViewById(R.id.ipTxt2);
		ipTxt3 = (TextView) findViewById(R.id.ipTxt3);
		ipTxt4 = (TextView) findViewById(R.id.ipTxt4);
		networkMaskTxt = (TextView) findViewById(R.id.networkMaskTxt);
		dnsTxt = (TextView) findViewById(R.id.dnsTxt);
		dns2Txt = (TextView) findViewById(R.id.dns2Txt);
		gatewayTxt = (TextView) findViewById(R.id.gatewayTxt);
		baudTxt = (TextView) findViewById(R.id.baudTxt);
		serverIpTxt = (TextView) findViewById(R.id.serverIpTxt);
		
		okBtn = (Button) findViewById(R.id.okBtn);
		backBtn = (Button) findViewById(R.id.backBtn);

		macTxt.setText(MyApplication.getMAC());
		if(NetworkUtil.isIpAddr(getKeyValue("ip"))){
			String ip[] = getKeyValue("ip").split("\\.");
			ipTxt1.setText(ip[0]);
			ipTxt2.setText(ip[1]);
			ipTxt3.setText(ip[2]);
			ipTxt4.setText(ip[3]);
		}
		
		serverIpTxt.setText(getKeyValue("serverip"));
		baudTxt.setText(getKeyValue("baud"));
		
		if(!mode.equals("autoSetServerIP")){
			networkMaskTxt.setText(getKeyValue("mask"));
			dnsTxt.setText(getKeyValue("dns"));
			dns2Txt.setText(getKeyValue("dns2"));
			gatewayTxt.setText(getKeyValue("gateway"));
		} else {
			networkMaskTxt.setEnabled(false);
			dnsTxt.setVisibility(View.INVISIBLE);
			dns2Txt.setVisibility(View.INVISIBLE);
			gatewayTxt.setVisibility(View.INVISIBLE);
			ipTxt1.setVisibility(View.INVISIBLE);
			ipTxt2.setVisibility(View.INVISIBLE);
			ipTxt3.setVisibility(View.INVISIBLE);
			ipTxt4.setVisibility(View.INVISIBLE);
		}


		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				updateConfig();
			}
		});

		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
	}
	
	//只是导入ip用的
	private void initViewForImportIp() {
		macTxt = (TextView) findViewById(R.id.macTxt);
		ipTxt1 = (TextView) findViewById(R.id.ipTxt1);
		ipTxt2 = (TextView) findViewById(R.id.ipTxt2);
		ipTxt3 = (TextView) findViewById(R.id.ipTxt3);
		ipTxt4 = (TextView) findViewById(R.id.ipTxt4);
		networkMaskTxt = (TextView) findViewById(R.id.networkMaskTxt);
		baudTxt = (TextView) findViewById(R.id.baudTxt);
		okBtn = (Button) findViewById(R.id.okBtn);
		backBtn = (Button) findViewById(R.id.backBtn);

		macTxt.setText(MyApplication.getMAC());
		serverIpTxt.setText(getKeyValue("serverip"));
		baudTxt.setText(getKeyValue("baud"));		
		String myIp = null;
		try {
			myIp = getIpFormImportFile(MyApplication.getMAC());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(NetworkUtil.isIpAddr(myIp)){
			String ip[] = myIp.split("\\.");
			ipTxt1.setText(ip[0]);
			ipTxt2.setText(ip[1]);
			ipTxt3.setText(ip[2]);
			ipTxt4.setText(ip[3]);
		}
		
		// networkMaskTxt.setText(getKeyValue("mask"));
		baudTxt.setText(getKeyValue("baud"));

		okBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				updateConfig();
			}
		});

		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
	}

	private String getIpFormImportFile(String mac) throws IOException {
		String ip = null;
		File file = new File(path);// Text文件
		BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
		String s = null;
		while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
			if (s.contains(mac)) {
				String info[] = s.split("-");
				ip = info[3];
			}
			System.out.println(s);
		}
		br.close();
		Log.i("setting", "getIpFormImportFile:" + ip);
		if (ip != null && ip.equals("null")) {
			ip = "";
		}
		return ip;
	}

	private void updateConfig() {
		
		// 设置服务器IP
		if (serverIpTxt.getText() != null && !serverIpTxt.getText().toString().equals("")) {
			String serverip = serverIpTxt.getText().toString();
			Log.i("setting", "服务器IP:" + serverip);
			
			SharedPreferencesConfig.setSpaServer(getBaseContext(), serverip);
			
			if (SharedPreferencesConfig.getSpaServer(getBaseContext()).equals(serverip)) {
				Toast.makeText(this, "服务器IP设置成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(this, "服务器IP设置失败", Toast.LENGTH_SHORT).show();
			}
		}
		
		// 设置波特率
		if (baudTxt.getText() != null && !baudTxt.getText().toString().equals("")) {
			Integer b = Integer.parseInt(baudTxt.getText().toString());
			if (b == 9600 || b == 19200 || b == 38400 || b == 115200) {
				SharedPreferencesConfig.setSerialBaud(getBaseContext(), b);
				if (SharedPreferencesConfig.getSerialBaud(getBaseContext()) == b) {
					Toast.makeText(this, "波特率设置成功", Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(this, "波特率设置失败", Toast.LENGTH_SHORT).show();
			}
		}
		
		//自动设置本地IP
		if(!mode.equals("autoSetServerIP")){
			String ip = ipTxt1.getText() + "." + ipTxt2.getText() + "." +ipTxt3.getText() + "." +ipTxt4.getText();
			String gateway = "0.0.0.0";
			String dns = "0.0.0.0";
			String dns2 = "0.0.0.0";
			String networkMask = "255.255.0.0";
			
			if (gatewayTxt.getText() != null && !gatewayTxt.getText().toString().equals("")) {
				gateway = gatewayTxt.getText().toString();
			}
			
			if (dnsTxt.getText() != null && !dnsTxt.getText().toString().equals("")) {
				dns = dnsTxt.getText().toString();
			}
			
			if (dns2Txt.getText() != null && !dns2Txt.getText().toString().equals("")) {
				dns2 = dns2Txt.getText().toString();
			}
			
			if (networkMaskTxt.getText() != null && !networkMaskTxt.getText().toString().equals("")) {
				networkMask = networkMaskTxt.getText().toString();
			}
			
		} else {
			//本地没权限，调用外面的apk辅助设置
			if(AppUtil.checkAppIsExist(this, Constants.SPA_HELPER_PACKET_NAME)){
				Intent intent = this.getPackageManager().getLaunchIntentForPackage(Constants.SPA_HELPER_PACKET_NAME);
				intent.putExtra("path", path);
				intent.putExtra("mode", "common");
				intent.putExtra("ipMacListPath", ipMacListPath);
		        this.startActivity(intent);
			}
		}

		if (!mode.equals("importIp") && !mode.equals("autoSetServerIP")) {
			updateProperties("ip", newIp);
			
			updateIpMacList(MyApplication.getMAC(),myIp);
			// 同步一下U盘
			WebInstaller.execCommand("sync");
		}
		
		finish();
	}

	private String updateNextIpToDist(String ip) {
		String num[] = ip.split("\\.");
		String newIp = ip;
		myIp = ip;
		
		Log.i("setting", "ip=" + ip);
		if (num.length == 4) {
			if (Integer.parseInt(num[3]) + 1 <= 253) {
				num[3] = String.valueOf(Integer.parseInt(num[3]) + 1);
			} else if (Integer.parseInt(num[2]) + 1 <= 253) {
				num[3] = "1";
				num[2] = String.valueOf(Integer.parseInt(num[2]) + 1);
			} else if (Integer.parseInt(num[1]) + 1 <= 253) {
				num[3] = "0";
				num[1] = String.valueOf(Integer.parseInt(num[1]) + 1);
			} else {
			}

			newIp = num[0] + "." + num[1] + "." + num[2] + "." + num[3];
			
			ipTxt1.setText(num[0]);
			ipTxt2.setText(num[1]);
			ipTxt3.setText(num[2]);
			ipTxt4.setText(num[3]);
		}

		Log.i("setting", "newIp = " + newIp + ":num.length=" + num.length);

		return newIp;
	}

	/**
	 * 读取属性文件中相应键的值
	 * 
	 * @param key
	 *            主键
	 * @return String
	 */
	public String getKeyValue(String key) {
		return props.getProperty(key);
	}

	/**
	 * 更新properties文件的键值对 如果该主键已经存在，更新该主键的值； 如果该主键不存在，则插件一对键值。
	 */
	public void updateProperties(String keyname, String keyvalue) {
		try {
			props.load(new FileInputStream(path));
			OutputStream fos = new FileOutputStream(path);
			props.setProperty(keyname, keyvalue);
			props.store(fos, "");
		} catch (IOException e) {
//			System.err.println("属性文件更新错误");
			Log.e("setting", "属性文件更新错误");
		}
	}

	/**
	 * 
	 */
	public void updateIpMacList(String keyname, String keyvalue) {
		try {
			Log.i("setting", "IP-MAC列表位置:" + ipMacListPath);
			
			List<String> buf = new ArrayList<String>();
			
			File file = new File(ipMacListPath);
			if (!file.exists()) {
				try {
					file.createNewFile();
					OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "GBK");
					write.write("1-" + keyname + "-" + keyvalue + "--开启" + "\r\n");
					
					write.close();
					
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}else{
				//全部读出来
				InputStreamReader read = new InputStreamReader(new FileInputStream(file),"GBK");//考虑到编码格式
				
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                
                while((lineTxt = bufferedReader.readLine()) != null){
                    System.out.println(lineTxt);
                    if(!lineTxt.contains(keyname)){
                    	//把读出来的全部放到一个bug上面
                    	if(!(lineTxt.equals("\r") || lineTxt.equals("\n"))){
                    		buf.add(lineTxt + "\r\n");
                    	}
                    }
                }
                
                buf.add(keyname + "-" + keyvalue + "--开启" + "\r\n");
                
                read.close();
                
                file.delete();
                
                WebInstaller.execCommand("sync");
                
                file.createNewFile();
				OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "GBK");
				
				int i = 1;
				for(String s : buf){
					//全部加序号
					write.write(i + "-" + s);
					i++;
				}
				
				write.close();
				
			}
		} catch (Exception e) {
//			System.err.println("IP-MAC列表文件更新错误");
			Log.e("setting", "IP-MAC列表文件更新错误");
		}
	}
}
